import re

from openai import OpenAI

from player.base.player import Player


"""
通义千问
网址：https://help.aliyun.com/zh/model-studio/new-free-quota?spm=a2c4g.11186623.help-menu-2400256.d_4_1.38642b60U4itF1
将申请到的key替换下方的api_key
"""
class QwenPlayer(Player):
    def __init__(self,api_key):
        super().__init__()
        self.api_key = api_key

    def step(self, board, pos, code, error_pos):
        prompt = f"这是当前的棋盘状态：\n{board}\n你是黑棋（黑棋为1,白棋为2），请建议下一个最佳落子点，不要有多余的话语，按照我的要求格式返回即可，返回格式为：(row, col)。"

        client = OpenAI(
            # 若没有配置环境变量，请用百炼API Key将下行替换为：api_key="sk-xxx",
            api_key=self.api_key,
            base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
        )

        response = client.chat.completions.create(
            model="qwen-max",  # 模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models
            messages=[
                {"role": "system", "content": "你是一个五子棋AI，负责为黑棋计算下一个最佳落子位置。"},
                {"role": "user", "content": prompt}
            ],
        )
        # 解析响应
        content = response.choices[0].message.content

        # 提取位置
        match = re.search(r'\((\d+), (\d+)\)', content)
        if match:
            row, col = int(match.group(1)), int(match.group(2))
            return (row, col)
        else:
            raise ValueError("无法解析AI返回的最佳落子位置")
